import Vue from 'vue';
import 'assets/style/global';
import qs from 'qs';
import axios from './utils/axios';
import ZeesuuService from '@zeesuu/service';
import APIs from 'config/API';
import Toast from './components/Toast';
import Confirm from './components/Confirm';
import VueClipboard from 'vue-clipboard2';

import MutongPv from 'mutong-pv';

Vue.use(VueClipboard);

Vue.prototype.$Toast = Toast;
Vue.prototype.$Confirm = Confirm;
Vue.prototype.$EventBus = new Vue();

import VueLazyLoad from 'vue-lazyload';
Vue.use(VueLazyLoad);

import AppJump from './directive/AppJump';
Vue.use(AppJump);

Vue.filter('imgSize', (url, w, h) => {
  if (!url) return;
  let a = '?x-oss-process=image/resize,m_fill';
  if (w) {
    a = a + ',w_' + w;
  }
  if (h) {
    a = a + ',h_' + h;
  }
  return url + a;
});

const toLogin = () => {
  const isLoginPage = window.location.href.indexOf('/login') > -1;
  if (!isLoginPage) {
    window.location.href = `/vita/login.html?redirect=${encodeURIComponent(window.location.href)}`;
  }
};

// 当做插件加载
Vue.use(MutongPv, {
  globalOption: {
    pt: '',
  },
});

const lowerUA = window.navigator.userAgent.toLowerCase();
Vue.prototype.$UA = {
  isJM: lowerUA.indexOf('jimu') > -1,
  isAndroid: lowerUA.match(/android/i),
  isIOS: lowerUA.match(/(iphone|ipod|ios)/i),
  isMobile: lowerUA.match(/(iphone|ipod|ios|android)/i),
  isWX: lowerUA.match(/micromessenger/i),
};

// 在PC/H5下要用这个来做环境
const query = qs.parse(window.location.search.replace(/^\?/, ''));
import JHWE from 'jimu-hybrid-web-environment';
Vue.use(JHWE, {
  callback: {
    network: axios,
    userInfo: async () => {
      try {
        const userInfo = await Vue.prototype.$service.UserInfo();
        return { code: 200, data: userInfo };
      } catch (err) {
        console.log(err);
        return err;
      }
    },
    toast: (data) => {
      Toast(data.msg);
    },
    login() {
      toLogin();
    },
    openLink(data) {
      if (data.target) {
        window.open(data.link, data.target);
      } else {
        window.location.href = data.link;
      }
    },
    alert(data) {
      window.alert(data.message);
    },
    setNav(data) {
      document.title = data.title;
      return Promise.resolve({
        code: 200,
        data: {},
      });
    },
    appInfo() {
      return Promise.resolve({
        data: { dark: 0 },
        code: 0,
      });
    },
    exit() {},
    pay(data) {
      const isWX = lowerUA.match(/micromessenger/i);
      if (isWX && !query.openId) {
        window.location.href =
          process.env.VUE_APP_BASE_URL +
          `/pay/getOpenId?redirectUrl=${window.btoa(window.location.href)}`;
      } else {
        Vue.prototype.$service
          .PayPrepayGo({
            ...data,
            payChannel: isWX ? 'wechatJsApi' : 'alipayWap',
            platform: 3,
          })
          .then((res) => {
            if (isWX) {
              const onBridgeReady = () => {
                WeixinJSBridge.invoke(
                  'getBrandWCPayRequest',
                  {
                    appId: res.appId, //公众号ID，由商户传入
                    timeStamp: res.timeStamp, //时间戳，自1970年以来的秒数
                    nonceStr: res.nonceStr, //随机串
                    package: res.package,
                    signType: res.signType, //微信签名方式：
                    paySign: res.paySign, //微信签名
                  },
                  (res) => {
                    if (res.err_msg == 'get_brand_wcpay_request:ok') {
                      Vue.prototype.$EventBus.$emit('paydone');
                    } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
                      Vue.prototype.$EventBus.$emit('paycancel');
                    } else {
                      Vue.prototype.$EventBus.$emit('payfailed');
                    }
                  },
                );
              };

              if (typeof WeixinJSBridge == 'undefined') {
                if (document.addEventListener) {
                  document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                  document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                  document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
              } else {
                onBridgeReady();
              }
            } else {
              document.querySelector('body').innerHTML = res.payUrl;
              document.forms[0].submit();
            }
          })
          .catch((err) => {
            Toast(err.message || '付款出错');
          });
      }
    },
  },
});

import appService from 'mutong-app-service';
Vue.use(appService);

Vue.use(
  { ...ZeesuuService },
  {
    apis: APIs,
    $http: Vue.prototype.$UA.isJM ? Vue.prototype.$appService.network : axios,
    isMini: !!Vue.prototype.$UA.isJM,
    debug: process.env.NODE_ENV === 'development',
  },
);

// 设置微信分享
!Vue.prototype.$UA.isJM &&
  Vue.prototype.$service &&
  Vue.prototype.$service
    .UserWechatJsapiTicket({ url: window.location.href })
    .then((res) => {
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: res.appId, // 必填，公众号的唯一标识
        timestamp: res.timestamp, // 必填，生成签名的时间戳
        nonceStr: res.nonceStr, // 必填，生成签名的随机串
        signature: res.signature, // 必填，签名，见附录1
        jsApiList: [
          'onMenuShareWeibo',
          'onMenuShareQZone',
          'updateTimelineShareData',
          'updateAppMessageShareData',
        ],
        openTagList: ['wx-open-launch-app'],
      });
      Vue.prototype.$setShareInfo = (data) => {
        const { imgUrl, desc, title, link } = data;
        wx.updateAppMessageShareData({
          title: title, // 分享标题
          desc: desc, // 分享描述
          link: link || window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: imgUrl, // 分享图标
          success: function () {},
        });
        wx.updateTimelineShareData({
          title: title, // 分享标题
          desc: desc, // 分享描述
          link: link || window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: imgUrl, // 分享图标
          success: function () {},
        });
      };
    })
    .catch((err) => {
      console.log(err);
    });

Vue.filter('hidePhone', (str) => {
  if (!str) return '';
  return str.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
});

Vue.config.ignoredElements = ['wx-open-launch-app'];

export default Vue;
